import { topicApi } from '/api/topic'
import { userApi } from '/api/user'
import { checkAuth, getDomoUser, getNotifications } from '/store/actions'
import { checkUserisVip, getServer, isLogin, vipTime } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event } from '/utils'
Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    user: {} as any,
    closeable: false,
    listInfo: [
      // {
      //   title: '加入的圈子',
      //   url: '/images/ico_me_following@2x.png',
      //   page: '/mine/topics/topics?type=joined',
      // },
      {
        title: '我的订单',
        url: '/images/mine_order@2x.png',
        page: '/mall/order/order',
      },
      {
        title: '联系客服  QQ号码：81102567',
        url: '/images/ico_me_question@2x.png',
        page: '/',
      },
      // {
      //   title: '我的赛事',
      //   url: '/images/ico_me_activity@2x.png',
      //   page: '/mine/myActivity/myActivity',
      // },
      // {
      //   title: '我的收藏',
      //   url: '/images/ico_me_collect@2x.png',
      //   page: '/mine/collections/collections',
      // },
      // {
      //   title: '我的设置',
      //   url: '/images/ico_me_settings@2x.png',
      //   page: '/mine/set/set',
      // },
      // {
      //   title: '我的客服',
      //   url: '/images/icon-myCustom.png',
      //   page: '/mine/customerService/customerService?type=1',
      // },
    ],
    notifications: {} as any,
    catList: [] as DomoTopic[],
    currencyName: GlobalData.currencyName,
    canCreate: false,
    create_permission: '',
    access: GlobalData.access,
    vipData: {} as DomoVip,
    logs: {},
    /** 是否过期 */
    expire: true,
    avatar: '',
  },
  async onLoad() {
    // $event.on('after:login', this, async () => {
    //   this.getUserInfo()
    // })
    // $event.on('logged', this, () => {
    //   this.getUserInfo()
    // })
    // $event.on('cancelRedDot', this, async () => {
    //   this.cancelReddot()
    // })
    // const vipData = await userApi.getVipConfig()
    // this.setData({
    //   navigationHeight: GlobalData.navigationHeight,
    //   vipData,
    // })
    // console.log('user on load2')
    // $event.on('message:showMessageDot', this, (isShow) => {
    //   if (typeof this.getTabBar === 'function' && this.getTabBar()) {
    //     this.getTabBar().setData({
    //       showMeesageDot: isShow,
    //     })
    //   }
    // })
    // $event.on('message:showMineDot', this, (isShow) => {
    //   if (typeof this.getTabBar === 'function' && this.getTabBar()) {
    //     this.getTabBar().setData({
    //       showMineDot: isShow,
    //     })
    //   }
    // })
  },
  async onShow() {
    // 自定义tab
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3,
      })
    }
    if (isLogin()) {
      getDomoUser()
    } else {
      checkAuth()
    }
    $event.on('after:boot', this, () => {
      this.setData({ access: GlobalData.access, currencyName: GlobalData.currencyName })
      // this.resolveCreateTopic()
    })
    this.setData!({
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
    })
    // this.resolveCreateTopic()
    // this.cancelReddot()
  },
  /** 消除tbar红点 */
  async cancelReddot() {
    getNotifications()
      .then((res) => {
        this.data.notifications.badges = res
        this.setData({
          notifications: this.data.notifications,
        })
      })
      .catch((err) => {
        console.log(err)
      })
  },
  resolveCreateTopic() {
    const {
      data: { user },
    } = this
    topicApi.getTopicConfig().then((data: TopicConfig) => {
      const {
        config: { create_permission },
      } = data

      this.setData({
        create_permission,
        canCreate:
          create_permission === 'all'
            ? true
            : create_permission === 'verification'
              ? !!user.verification
              : true,
      })
    })
  },
  async mySet() {
    wx.navigateTo({
      url: '/mine/set/set',
    })
  },
  /** 复制邀请码 */
  async Invitecode() {
    wx.navigateTo({
      url: `/mine/invite/invite`,
    })
  },
  /**
   * 获取用户信息及用户圈子
   */
  async getUserInfo() {
    const user = wx.getStorageSync(`${getServer()}/logged`).data || {}
    const { id }: { id: number } = user
    const catList = await topicApi.getUserTopics({ for_user: id, limit: 4, status: 'all' })
    let exclude = ''
    catList.forEach((item) => {
      exclude += item.id + ','
    })
    const logs = await userApi.joinTopicLogs({
      exclude,
    })
    let expire = true
    if (user.vip) {
      expire = !checkUserisVip(user)
      const time = new Date(user.vip.end_time)
      user.vipTime = vipTime(time)
    }
    const avatar = user.avatar
      ? user.avatar.url || user.avatar
      : `/images/${user.sex == 1 ? 'famale_male' : user.sex == 2 ? 'famale_female' : 'default_unknow'
      }@2x.png`
    this.setData({
      avatar,
      user,
      catList,
      logs,
      expire,
    })
  },
  /**
   * 个人页面
   * @param e
   */
  toHomePage(e: any) {
    wx.navigateTo({
      url: `/mine/homePage2/homePage2?id=${e.currentTarget.dataset.id}`,
    })
  },
  /**
   * 圈子创建页面
   */
  toCreateTopic() {
    const {
      data: { canCreate, create_permission },
    } = this
    if (!canCreate) {
      wx.showModal({
        title: '提示',
        content:
          create_permission === 'verification'
            ? '认证用户才能创建圈子'
            : '无法创建圈子，请联系管理员',
      })
      return
    }
    wx.navigateTo({
      url: `/mine/create-topic/create-topic`,
    })
  },
  /**
   * 进入圈子列表
   */
  goToTopics() {
    const {
      data: {
        user: { id },
      },
    } = this
    wx.navigateTo({
      url: `/mine/topics/topics?user=${id}`,
    })
  },
  goToPage(e: any) {
    const {
      currentTarget: {
        dataset: { page },
      },
    } = e
    wx.navigateTo({
      url: page,
    })
  },
  /**
   * 粉丝/关注页面
   * @param e
   */
  handleFollow(e: any) {
    const {
      currentTarget: {
        dataset: { page },
      },
    }: { currentTarget: any; page: string } = e
    const hasfolling = page === 'follower'
    wx.navigateTo({
      url: `/mine/follow/follow?type=${page}&&hasfolling=${hasfolling}`,
    })
  },
  /**
   * 进入个人设置页面
   */
  goToProfileSetting() {
    wx.navigateTo({
      url: '/mine/setting/setting',
    })
  },
  goToUserVerify() {
    wx.navigateTo({
      url: '/mine/user-verified/user-verified',
    })
  },
  goToOrgVerify() {
    wx.navigateTo({
      url: '/mine/org-verified/org-verified',
    })
  },
  goToRefused(e: any) {
    const {
      target: {
        dataset: { type },
      },
    } = e
    switch (type) {
      case 'user':
        wx.navigateTo({
          url: '/mine/add-user-verification/add-user-verification?load=1',
        })
        break
      case 'org':
        wx.navigateTo({
          url: '/mine/add-org-verification/add-org-verification?load=1',
        })
        break
    }
  },
  showVerifiyEntry() {
    wx.showActionSheet({
      itemList: ['球员认证', '裁判认证'],
      success: ({ tapIndex }) => {
        wx.navigateTo({
          url: `/mine/add-${tapIndex === 0 ? 'user' : 'org'}-verification/add-${tapIndex === 0 ? 'user' : 'org'
            }-verification`,
        })
      },
    })
  },
  toTopic(e: WechatMiniprogram.BaseEvent) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({ url: `/pages/topic/detail/detail?topicId=${id}` })
  },
  /** 跳转Vip */
  vip() {
    if (GlobalData.system == 'ios') {
      wx.showToast({
        title: '由于相关规范，iOS功能暂不可用',
        icon: 'none',
      })
      return
    }
    wx.navigateTo({
      url: '/mine/vip/vip',
    })
  },
  onHide() { },
})
